/**
 * <b>项目名：</b>贵州刑侦社会资源采集<br/>
 * <b>包名：</b>com.iflytek.utils<br/>
 * <b>文件名：</b>TransferUtil.java<br/>
 * <b>版本信息：</b><br/>
 * <b>日期：</b>2012-4-22-下午02:07:04<br/>
 * <b>Copyright (c)</b> 科大讯飞2012-版权所有<br/>
 * 
 */
package com.iflytek.ci.common;

import com.iflytek.ci.base.SysCode;
import com.iflytek.iframework.business.cache.impl.PublicZdCacheLoadImpl;
import com.iflytek.iframework.orm.Page;
import com.iflytek.iframework.utils.DateUtils;
import com.iflytek.iframework.utils.StringUtils;
import net.sf.json.JSONArray;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 转换工具
 * 
 * @author hyzha
 * 
 */
public class TransferUtil {

    /**
     * 单位编码截取位置
     */
    private static final int ORGCODE_SUBINDEX = 6;

    /**
     * @Title: transferOrgCode
     * @Description: 转换单位编码,截取前六位
     * @param orgCode
     *            单位编码
     * @return String
     * @throws
     */
    public static String transferOrgCode(String orgCode) {
        return StringUtils.substring(orgCode, 0, ORGCODE_SUBINDEX);
    };

    /**
     * @Title: getJartJsonResultFromList
     * @Description: 返回当前页面的JArt 调用的JSON值
     * @param list
     *            列表
     * @return String json对象
     * @throws
     */
    public static String getJartJsonResultFromList(List<?> list) {
        if (list == null || list.isEmpty()) {
            return "{total:0,rows:[]}";
        }
        return "{total:" + list.size() + ",rows:" + JSONArray.fromObject(list)
                + "}";
    }

    /**
     * @Title: transferDate
     * @Description: 转换时间
     * @param date
     *            时间
     * @param dateFormat
     *            入参时间格式化
     * @param outDateFormat
     *            出参时间格式化
     * @return String
     * @throws
     */
    public static String transferDate(String date) {
        String result = "";
        if (StringUtils.isNotBlank(date)) {
            String[] s1 = date.split(" ");
            String[] s2 = s1[0].split("-");
            result += s2[0] + (s2[1].length() == 1 ? "0" : "") + s2[1]
                    + (s2[2].length() == 1 ? "0" : "") + s2[2];
            if (s1.length == 2) {
                String[] s3 = s1[1].split(":");
                result += (s3[0].length() == 1 ? "0" : "") + s3[0]
                        + (s3[1].length() == 1 ? "0" : "") + s3[1]
                        + (s3[2].length() == 1 ? "0" : "") + s3[2];
            }
        }
        return result;
    }

    /**
     * 将公安部的“重点人员类别”转为字典项里的类别编码，多个以“,”隔开
     * 
     * @param str
     * @return
     */
    public static String toRylb(String str) {
        if (str == null || "".equals(str))
            return "";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 7; i++) {
            if ("1".equals(str.substring(i, (i + 1)))) {
                if (sb != null && sb.length() > 0)
                    sb.append(",");
                sb.append("0" + (i + 1));
                sb.append("0000000000");
            }
        }
        return sb.toString();
    }

    /**
     * 
     * 转换人员来源
     * 
     * @param ryly
     * @return
     * @author hyzha@iflytek.com
     * @created 2012-5-14 下午08:16:55
     * @lastModified
     * @history
     */
    public static String transferRylys(String ryly) {
        if (StringUtils.isBlank(ryly)) {
            return "";
        }
        char[] dm = new char[8];
        for (int i = 0; i < dm.length; i++) {
            dm[i] = '0';
        }
        String[] bj = ryly.split(",");
        for (int i = 0; i < bj.length; i++) {
            int p = getBitPos(bj[i]);
            if (p >= 0) {
                dm[p] = '1';
            }
        }
        return String.copyValueOf(dm);
    }

    /**
     * 
     * ｛转换人员来源从字符分割到数组｝
     * 
     * @param ryly
     * @return
     * @author jbyu
     * @created 2012-5-18 下午02:18:37
     * @lastModified
     * @history
     */
    public static List<String> transferRylyToArray(String ryly) {
        if (StringUtils.isEmpty(ryly))
            ryly = "00000000";
        List<String> result = new ArrayList<String>();
        for (int i = 0; i < 8; i++) {
            if ("1".equals(ryly.substring(i, (i + 1)))) {
                result.add("" + (i + 1));
            }
        }
        // Collections.sort(result);
        return result;
    }

    /**
     * 
     * ｛转换人员来源从8位编码分割到字符串｝
     * 
     * @param ryly
     * @return
     * @author jbyu
     * @created 2012-5-18 下午02:18:37
     * @lastModified
     * @history
     */
    public static String toRylbArray(String str) {
        if (StringUtils.isEmpty(str))
            str = "00000000";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            if ("1".equals(str.substring(i, (i + 1)))) {
                if (sb != null && sb.length() > 0)
                    sb.append(",");
                sb.append("" + (i + 1));
            }
        }
        return sb.toString();
    }

    /**
     * 
     * 获取标识位 <br>
     * 
     * @param ryly
     * @return
     * @author hyzha@iflytek.com
     * @created 2012-5-14 下午08:30:19
     * @lastModified
     * @history
     */
    public static int getBitPos(String ryly) {
        ryly = ryly.replaceAll("^(0)*", "");
        if (StringUtils.isBlank(ryly)) {
            return -1;
        }
        int p = Integer.parseInt(ryly);
        return p - 1;
    }

    /**
     * 比较层级类别编码，将父级编码去零后，类别编码符合子级编码
     * 
     * @param lbbm
     *            类别编码
     * @param staticLb
     *            标准父级编码
     * @return
     */
    public static boolean compareNewLbbm(String lbbm, String staticLb) {
        if (StringUtils.isNotBlank(lbbm) && StringUtils.isNotBlank(staticLb)) {
            return lbbm.substring(0,
                    StringUtils.toNewsOrgCode(staticLb).length()).equals(
                    StringUtils.toNewsOrgCode(staticLb));
        }
        return false;

    }

    /**
     * 
     * ｛获取名称支持多个编码｝
     * 
     * @param lxjp
     * @param code
     * @return
     * @author jbyu
     * @created 2012-5-21 上午09:54:51
     * @lastModified
     * @history
     */
    public static String getZdmc(String lxjp, String code) {
        if (StringUtils.isEmpty(lxjp) || StringUtils.isEmpty(code)
                || StringUtils.split(code, ",").length == 0) {
            return StringUtils.EMPTY;
        }
        if (code.indexOf(",") != -1) {
            String[] codes = code.split(",");
            StringBuilder str = new StringBuilder();
            for (int i = 0; i < codes.length; i++) {
                String string = PublicZdCacheLoadImpl.getDictMc(lxjp, codes[i],
                        false);
                if (i != codes.length - 1) {
                    str.append(string).append(",");
                } else {
                    str.append(string);
                }
            }
            return str.toString();
        } else {
            return PublicZdCacheLoadImpl.getDictMc(lxjp, code, false);
        }
    }

    /**
     * 
     * ｛查询数据库 一个子段存储多个值，查询包含关系的sql｝
     * 
     * @param column
     * @param param
     * @return
     * @author jbyu
     * @created 2012-5-22 下午02:11:22
     * @lastModified
     * @history
     */
    public static String popuHqlREGEXP_LIKE(String column, String param) {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(param)) {
            sb.append(" and ").append("regexp_like (").append(column).append(
                    ",'^").append(StringUtils.toNewsOrgCode(param))
                    .append("')");
        }
        return sb.toString();
    }

    /**
     * 
     * ｛去除尾部0｝
     * 
     * @param code
     * @return
     * @author jbyu
     * @created 2012-5-22 上午11:47:29
     * @lastModified
     * @history
     */
    public static String replace_number0(String code) {
        if (StringUtils.isBlank(code)) {
            return "";
        }
        while ("0".equals(code.substring(code.length() - 1))) {
            code = code.substring(0, code.length() - 1);
        }
        return code;
    }

    public static String replaceRylys(String rylys, String ryly) {
        Integer ll = Integer.parseInt(ryly);
        rylys = rylys.substring(0, ll - 1) + "1" + rylys.substring(ll);
        return rylys;
    }

    /**
     * 
     * ｛查询包括下级的正则表达式｝
     * 
     * @author jbyu
     * @created 2012-5-24 下午06:45:23
     * @lastModified
     * @history
     */
    public static String getRegexp(String str, int num) {
        String exp = replace_number0(str);
        int zw = num - exp.length();
        return exp + "[0-9]{" + zw + "}";
    }

    /**
     * 获取统计时的行政区划
     * 
     * @param dwbm
     *            6位的编码
     * @return
     * @author Administrator
     * @created 2012-6-4 下午06:42:18
     * @lastModified
     * @history
     */
    public static String getStatisticsXzqh(String xzqh) {
        if (StringUtils.isEmpty(xzqh))
            return StringUtils.EMPTY;
        if (xzqh.length() < 6) {
            xzqh += "000000";
            xzqh = xzqh.substring(0, 6);
        }
        if (xzqh.substring(2, 4).equals("00")) {
            xzqh = new StringBuilder(xzqh.substring(0, 2)).append("__").append(
                    xzqh.substring(4, xzqh.length())).toString();
        } else if (xzqh.substring(4, 6).equals("00")) {
            xzqh = new StringBuilder(xzqh.substring(0, 4)).append("__")
                    .toString();
        }
        return xzqh;
    }

    /**
     * 获取统计时用到的行政区划的长度
     * 
     * @param xzqh
     *            行政区划
     * @return
     * @author Administrator
     * @created 2012-6-5 下午12:17:17
     * @lastModified
     * @history
     */
    public static int getStatisticsOrgCodeLength(String xzqh) {
        int JGBMLength = StringUtils.toNewsOrgCode(xzqh).length();
        // JGBMLength = JGBMLength < 6 ? JGBMLength + 2 : JGBMLength;
        return JGBMLength;
    }

    /**
     * 获取count查询的sql
     * 
     * @param sql
     *            原sql语句
     * @return 查询语句
     * @author Administrator
     * @created 2012-6-7 上午10:51:50
     * @lastModified
     * @history
     */
    public static String getTotalCountSql(String sql) {
        return "select count(*) from (" + sql + ")";
    }

    /**
     * 分页sql
     * 
     * @param sql
     * @param page
     * @return
     * @author Administrator
     * @created 2012-6-4 下午04:00:44
     * @lastModified
     * @history
     */
    public static String getPageSql(String sql, Page<?> page) {
        String querySql = "Select * From ( Select x.*, Rownum rn From (" + sql
                + "  ) x Where Rownum <= "
                + (page.getPageSize() * page.getCurrentPageNo()) + " )"
                + " Where rn >  "
                + (page.getPageSize() * (page.getCurrentPageNo() - 1));
        return querySql;
    }

    /**
     * 
     * ｛二个数相加｝
     * 
     * @param b1
     * @param b2
     * @return
     * @author jbyu
     * @created 2012-8-2 上午11:40:04
     * @lastModified
     * @history
     */
    public static BigDecimal addBigDecimal(BigDecimal b1, BigDecimal b2) {
        if (b1 == null) {
            b1 = new BigDecimal(0);
        }
        if (b2 == null) {
            b2 = new BigDecimal(0);
        }
        return b1.add(b2);
    }

    /**
     * 查询的开始时间,按日期日期格式查询
     * 
     * @param queryCondition
     * @return
     */
    public static String popuBeginDateHql(String coloumn, String queryCondition) {
        StringBuilder sb = new StringBuilder();
        if (!StringUtils.isEmpty(queryCondition)) {
            sb.append(" and ").append(coloumn).append(" >=to_date('").append(
                    queryCondition + "','YYYY-MM-DD HH24:MI:SS') ");
        }
        return sb.toString();
    }

    /**
     * 查询的开始时间,按日期日期格式查询
     * 
     * @param queryCondition
     * @return
     */
    public static String popuEndDateHql(String coloumn, String queryCondition) {
        StringBuilder sb = new StringBuilder();
        if (!StringUtils.isEmpty(queryCondition)) {
            sb.append(" and ").append(coloumn).append(" <=to_date('").append(
                    queryCondition + "','YYYY-MM-DD HH24:MI:SS') ");
        }
        return sb.toString();
    }

    /**
     * 查询的开始时间,按日期日期格式查询
     * 
     * @param coloumn
     * @param queryCondition
     * @return String
     */
    public static String popuBeginDateSql(String coloumn, String queryCondition) {
        StringBuilder sb = new StringBuilder();
        if (!StringUtils.isBlank(queryCondition)) {
            sb.append(" and ").append(coloumn).append(" >=to_date('").append(
                    queryCondition + "000000','yyyymmddhh24miss') ");
        }
        return sb.toString();
    }

    /**
     * 查询的开始时间,按日期日期格式查询
     * 
     * @param coloumn
     * @param queryCondition
     * @return String
     */
    public static String popuEndDateSql(String coloumn, String queryCondition) {
        StringBuilder sb = new StringBuilder();
        if (!StringUtils.isBlank(queryCondition)) {
            sb.append(" and ").append(coloumn).append(" <=to_date('").append(
                    queryCondition + "235959','yyyymmddhh24miss') ");
        }
        return sb.toString();
    }

    /**
     * 获取当月的第一天0点
     * 
     * @param time
     *            6位数时间 格式：yyyyMM
     * @return 返回6位时间格式
     * @author Administrator
     * @created 2012-11-23 下午02:11:59
     * @lastModified
     * @history
     */
    @SuppressWarnings("deprecation")
    public static String getMinTime(String time) {
        Calendar cDay1 = Calendar.getInstance();
        cDay1.setTime(DateUtils.toDate(time, "yyyyMM"));
        int lastday = cDay1.getActualMinimum(Calendar.DAY_OF_MONTH);
        Date lastDate = cDay1.getTime();
        lastDate.setDate(lastday);
        return DateUtils.parseDate(lastDate, SysCode.DATESTR_FORMATTER_S);
    }

    /**
     * 获取当月的最后一天23:59:59点
     * 
     * @param time
     *            6位数时间 格式：yyyyMM
     * @return 返回6位时间格式
     * @author Administrator
     * @created 2012-11-23 下午02:12:28
     * @lastModified
     * @history
     */
    @SuppressWarnings("deprecation")
    public static String getMaxTime(String time) {
        Calendar cDay1 = Calendar.getInstance();
        cDay1.setTime(DateUtils.toDate(time, "yyyyMM"));
        int lastday = cDay1.getActualMaximum(Calendar.DAY_OF_MONTH);
        Date lastDate = cDay1.getTime();
        lastDate.setDate(lastday);
        return DateUtils.parseDate(lastDate, SysCode.DATESTR_FORMATTER_S);
    }

    /**
     * 
     * ｛转义url的%｝
     * 
     * @param str
     * @return
     * @author Administrator
     * @created 2012-7-19 下午03:23:27
     * @lastModified
     * @history
     */
    public static String URLEncoder(String str) {
        String result = "";
        try {
            result = java.net.URLEncoder.encode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 计算两个日期之间相差的天数
     * 
     * @param date1
     * @param date2
     * @return
     */
    public static int daysBetween(Date date1, Date date2) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);
        long time1 = cal.getTimeInMillis();
        cal.setTime(date2);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 获取月份的天数
     * 
     * @param date
     *            日期
     * @return 天数
     * @author Administrator
     * @created 2012-12-23 下午05:10:50
     * @lastModified
     * @history
     */
    public static int getDaysByMonth(Date date) {
        Calendar cc = Calendar.getInstance();
        cc.setTime(date);
        return cc.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取时分秒的秒数
     * 
     * @param date
     * @return
     * @author Administrator
     * @created 2012-12-24 下午02:05:18
     * @lastModified
     * @history
     */
    @SuppressWarnings("deprecation")
    public static int parseHourToSecond(Date date) {
        return (date.getHours() * 3600) + (date.getMinutes() * 60)
                + date.getSeconds();
    }

    /**
     * 组装 like '%xxxx'
     * 
     * @param column
     * @param param
     * @return
     * @author Administrator
     * @created 2012-6-12 上午09:55:42
     * @lastModified
     * @history
     */
    public static String popuHqlLlike(String column, String param) {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(param)) {
            sb.append(" and ").append(column).append(" like '").append("%")
                    .append(param.trim()).append("' ");
        }
        return sb.toString();
    }

    /**
     * 拼 in查询
     * 
     * @param column
     * @param param
     * @return
     * @author Administrator
     * @created 2013-1-16 下午08:07:48
     * @lastModified
     * @history
     */
    public static String popuHqlIn(String column, String param) {
        if (StringUtils.isNotBlank(param)) {
            StringBuilder sb = new StringBuilder(" and ").append(column)
                    .append(" in (");
            String[] arr = StringUtils.split(param, ",");
            for (int i = 0; i < arr.length; i++) {
                if (i > 0) {
                    sb.append(",");
                }
                sb.append("'").append(arr[i]).append("'");
            }
            sb.append(")");
            return sb.toString();
        }
        return StringUtils.EMPTY;
    }

    
    /**
     * 
     * ｛说明该函数的含义和作用，如果函数较为复杂，请详细说明｝
     * 
     * @param orgcode
     * @return
     * @author scrum
     * @created 2013-6-3 下午10:58:28
     * @lastModified
     * @history
     */
    public static String toNewsOrgCode(String orgcode) {
        if (isNotEmpty(orgcode)) {
            boolean temp = false;
            orgcode = orgcode.replace("\r", "");
            orgcode = orgcode.replace("\n", "");
            do {
                if (orgcode.length() > 2) {
                    String newstr = orgcode.substring(orgcode.length() - 2);
                    if ("00".equals(newstr)) {
                        orgcode = orgcode.substring(0, orgcode.length() - 2);
                    } else {
                        temp = true;
                    }
                } else {
                    temp = true;
                }
            } while (!temp);
        }
        return orgcode;
    }

    /**
     * 
     * ｛说明该函数的含义和作用，如果函数较为复杂，请详细说明｝
     * 
     * @param str
     * @return
     * @author scrum
     * @created 2013-6-3 下午10:58:35
     * @lastModified
     * @history
     */
    public static boolean isEmpty(String str) {
        return (str == null || StringUtils.isBlank(str));
    }

    /**
     * 
     * ｛说明该函数的含义和作用，如果函数较为复杂，请详细说明｝
     * 
     * @param str
     * @return
     * @author scrum
     * @created 2013-6-3 下午10:58:39
     * @lastModified
     * @history
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

}
